import { createRouter, createWebHistory, type RouteRecordRaw, type RouteRecordRedirectOption } from 'vue-router'
import { useUserStore } from '../store/user'
import Layout from '../layout/index.vue'
import { getPageTitle } from '../utils/common'
import { DashboardOutlined, SettingOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons-vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/login/index.vue'),
      meta: { title: '登录', hidden: true }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard/index',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../views/dashboard/index.vue'),
          meta: { 
            title: '首页', 
            icon: DashboardOutlined
          }
        }
      ]
    },
    {
      path: '/system',
      component: Layout,
      meta: { title: '系统管理', icon: SettingOutlined },
      children: [
        {
          path: 'user',
          name: 'User',
          component: () => import('../views/system/user/index.vue'),
          meta: { title: '用户管理', icon: UserOutlined }
        },
        {
          path: 'role',
          name: 'Role',
          component: () => import('../views/system/role/index.vue'),
          meta: { title: '角色管理', icon: TeamOutlined }
        }
      ]
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/error/404.vue'),
      meta: { title: '404', hidden: true }
    }
  ]
})

// 定义动态路由的类型

export interface DynamicRouteComponent {
  path: string;
  name?: string;
  component: any;
  redirect?: RouteRecordRedirectOption;
  meta?: Record<string, any>;
  children?: DynamicRouteComponent[];
}

// 记录是否已添加动态路由
let dynamicRoutesAdded = false

// 动态添加路由的方法
export const addRoutes = (routes: DynamicRouteComponent[]) => {
  routes.forEach(route => {
    const resolvedRoute = { ...route } as RouteRecordRaw
    
    // 处理组件
    if (route.component === 'Layout') {
      resolvedRoute.component = Layout
    } else if (typeof route.component === 'string') {
      const componentPath = route.component
      resolvedRoute.component = () => import(`..${componentPath}.vue`)
    }

    if (route.children) {
      resolvedRoute.children = route.children.map((child: any) => ({
        ...child,
        component: child.component
      }))
    }

    router.addRoute(resolvedRoute)
  })
  dynamicRoutesAdded = true
}

// 重置路由
export const resetRouter = () => {
  const newRouter = createRouter({
    history: createWebHistory(),
    routes: router.options.routes
  })
  // @ts-ignore
  router.matcher = newRouter.matcher
  dynamicRoutesAdded = false
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = getPageTitle(to.meta.title as string)
  
  const userStore = useUserStore()
  const token = userStore.token
  
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      try {
        if (!userStore.hasUserInfo || !dynamicRoutesAdded) {
          // 获取用户信息
          await userStore.getUserInfoAction()
          // 获取动态路由
          const routes = await userStore.getRoutesAction()
          // 添加动态路由
          addRoutes(routes)
          // 确保路由已添加完成
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (error) {
        // 出错时登出
        resetRouter()
        await userStore.logout()
        next('/login')
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router 